package cn.blue.base.interceptor;

import cn.blue.base.annotation.PreAuthorize;
import cn.blue.base.jwt.JwtUtils;
import cn.blue.base.jwt.Payload;
import cn.blue.base.jwt.RsaUtils;
import cn.blue.base.jwt.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Slf4j
@Component//此注解把登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("4444444444444444444444444");
//        // 为空 我们要返回 {"success":false,"resultObj":"nologin"}
//        // 3.1.设置编码字符集
//        response.setCharacterEncoding("UTF-8");
//        // 3.2.设置响应参数类型为JSON
//        response.setContentType("application/json;charset=UTF-8");
//        // 获取到token
//        String token = request.getHeader("token");
//        // 判断token是否存在
//        if (StringUtils.isNotBlank(token)){
//            // 去redis中拿 用户信息
////            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
//            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
////            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
////            UserInfo userInfo = payload.getUserInfo();
//            return true;
//        }
//        // 3.3.获取到打印流,并设置响应数据
//        PrintWriter writer = response.getWriter();
//        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
//        // 3.4.刷新、关流
//        writer.flush();
//        writer.close();
//
//        return false;
//    }
        log.info("4444444444444444444444444");
        // 为空 我们要返回 {"success":false,"resultObj":"nologin"}
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 获取到token
        String token = request.getHeader("token");
        // 判断token是否存在
        if (StringUtils.isNotBlank(token)){
            // 去redis中拿 用户信息
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
            //    PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            // 判断信息是否存在
            if (null != userInfo.getLogininfo()){
                if (0 == userInfo.getLogininfo().getType()){
                    // 如果是后台人员 需要判断权限
                    // 获取到当前的请求方法
                    HandlerMethod method = (HandlerMethod) handler;
                    // 获取到方法上的注解 PreAuthorize
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (null != annotation){
                        // 方法上配置的sn
                        String sn = annotation.sn();
                        // 查询当前用户拥有哪些权限
//                        List<String> snList =  permissionMapper.findByLogininfoId(userInfo.getLogininfo().getId());
                        List<String> snList = userInfo.getPermissions();
                        if (!snList.contains(sn)){
                            // 不在
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                    return true;
                }
                // 存在 重置redis的过期时间
//                redisTemplate.expire(token,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();

        return false;
    }
}
